using SmartCommunity.Models;
using Mapster;
using Microsoft.EntityFrameworkCore;

namespace SmartCommunity.Services.Workorder
{
    /// <summary>
    /// 服务类：工单处理过程记录
    /// </summary>
    public class WorkProcessService : BaseService<WorkProcessEntity>
    {
        #region 构造函数
        protected readonly SCDBContext ctx;
        public WorkProcessService(SCDBContext ctx)
        {
            this.ctx = ctx;
        }
        #endregion

        #region 数据查询 
        /// <summary>
        /// 分页查询
        /// </summary>
        public async Task<PageResult<WorkProcessDto>> FindPagedList(WorkProcessQuery workProcessQuery, Pager pager, LoginUser user)
        {
            var query = ctx.WorkProcesses.AsNoTracking().Where(workProcessQuery.GetQueryExpression());
            var data = await FindPagedList(query, pager, o => o.OrderByDescending(t => t.CreatedTime));
            return data.Map(o => o.Adapt<WorkProcessDto>());
        }

        /// <summary>
        /// 根据工单处理过程记录ID查询
        /// </summary>
        public async Task<WorkProcessDto> FindWorkProcessById(Guid processId)
        {
            var entity = await FindById(processId);
            return entity.Adapt<WorkProcessDto>();
        }

        /// <summary>
        /// 根据ID查询实体类
        /// </summary>
        private async Task<WorkProcessEntity> FindById(Guid id)
        {
            return await ctx.WorkProcesses.SingleOrDefaultAsync(a => a.ProcessId == id)
                ?? throw new NotFoundException($"找不到指定的工单处理过程记录,Id:{id}");
        }
        #endregion

        #region 增 删 改
        /// <summary>
        /// 新增工单处理过程记录
        /// </summary>
        public async Task<WorkProcessDto> CreateWorkProcess(WorkProcessDto dto, LoginUser user)
        {
            // 新建对象
            var entity = new WorkProcessEntity();
            // 复制属性
            await CopyDtoToEntity(dto, entity, user, true);
            // 执行保存
            ctx.WorkProcesses.Add(entity);
            await ctx.SaveChangesAsync();
            // 返回Dto
            return entity.Adapt<WorkProcessDto>();
        }

        /// <summary>
        /// 更新工单处理过程记录
        /// </summary>
        public async Task UpdateWorkProcess(WorkProcessDto dto, LoginUser user)
        {
            // 原始数据
            var entity = await FindById(dto.ProcessId);
            // 更新字段
            await CopyDtoToEntity(dto, entity, user, false);
            // 执行更新
            await ctx.SaveChangesAsync();
        }

        /// <summary>
        /// 复制dto属性到实体字段
        /// </summary>
        private async Task CopyDtoToEntity(WorkProcessDto dto, WorkProcessEntity entity, LoginUser user, bool isNew)
        {
            //TODO 检查数据重复
            if (await ctx.WorkProcesses.AnyAsync(a => a.ProcessId != dto.ProcessId /* && (a.Name == dto.Name )*/))
            {
                throw new MessageException("当前已存在相同名称或编码的工单处理过程记录");
            }
            entity.OrderId = dto.OrderId;
            entity.Content = dto.Content;

            // 记录操作人
            if (isNew)
            {
                entity.CreatedBy = user.Username;
                entity.CreatedTime = DateTime.Now;
            }
            entity.UpdatedBy = user.Username;
            entity.UpdatedTime = DateTime.Now;
        }

        /// <summary>
        /// 根据ID删除工单处理过程记录
        /// </summary>
        public async Task DeleteByIds(IEnumerable<Guid> ids, LoginUser user)
        {
            var workProcesses = await ctx.WorkProcesses.Where(a => ids.Contains(a.ProcessId)).ToListAsync();
            if (workProcesses.Count != ids.Count())
            {
                throw new MessageException("查询出的数据和传入的ID不匹配，请刷新后再试。");
            }
            //TODO 判断是否能删除
            foreach (var entity in workProcesses)
            {
                ctx.WorkProcesses.Remove(entity);
            }
            // 提交事务
            await ctx.SaveChangesAsync();
        }
        #endregion
    }
}
